package app.cms.machining;

import java.io.File;
import java.sql.Connection;
import java.util.Map;

import jt.classic.system.context.ISystemContext;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.user.IUser;
import jt.classic.system.utils.BaseworkSelectUtil;

import org.limp.basework.MachiningException;
import org.limp.basework.SimpleBean;
import org.limp.basework.SimpleBean4Table;
import org.limp.basework.SimpleBeanMachining;
import org.limp.basework.Table;
import org.limp.basework.console.XSystemConfig;
import org.limp.basework.impl.CommonBean4HSQ;
import org.limp.basework.impl.SimpleBean4TableImpl;
import org.limp.basework.tools.BaseworkUtil;
import org.limp.mine.DataTrimmerI;
import org.limp.mine.DateTrimmer;
import org.limp.mine.FileTool;
import org.limp.mine.StringTool;

/**
 * 内容信息加工
 * 
 * @author mido
 * 
 */
public class InfoMachining implements SimpleBeanMachining {
	private static String realpath = (String) XSystemConfig.config()
			.getProperty(XSystemConfig.XSYSTEM_REALPATH);

	public SimpleBean machining(SimpleBean bean, Table table,
			CommonBean4HSQ cbh, Connection conn, int type)
			throws MachiningException {
		// TODO Auto-generated method stub
		if (ISystemContext.invalidSesstion(cbh.getRequest())) {
			throw new MachiningException("invalid session error.");
		}

		if (type == -1) {
			// before insert
			IUser user = ISystemContext.getSessionUser(cbh.getRequest());

			bean.getResource().put("I_DATE", DateTrimmer.getYMDHMS());
			bean.getResource().put("I_STATUS", "1");
			bean.getResource().put("I_USERID", user.id());
			bean.getResource().put("I_USERNAME", user.iname());
		} else if (type == -2) {
			// before update
			bean.getResource().put("I_UDPATEDATE", DateTrimmer.getYMDHMS());
			
			String infoid = (String) bean.getResource().get("PK_ID");
			this.deleteHTMLFile(infoid, conn);
		} else if (type == 0 || type == 1) {
			// after insert or update
			String infoid = (String) bean.getResource().get("PK_ID");

			// 暂存infoid为后续操作使用
			cbh.getResource().put("infoId", infoid);

			String title = (String) bean.getResource().get("I_TITLE");
			String key = (String) bean.getResource().get("I_KEYS");
			String desc = (String) bean.getResource().get("I_DESC");
			String categoryId = (String) bean.getResource().get("D_ID");
			String template = (String) bean.getResource().get("D_TEMPLATEID");
			String HTMLString = (String) bean.getResource().get("I_CONTENT");
			// 静态页面模板根目录
			File templateFolder = new File(realpath, FileTool.wash(
					"app.cms.template", "."));
			// 静态页面模板
			File templateFile = new File(templateFolder, template);
			if (templateFile.exists()) {
				// 读取页面模板
				String templateHTML = FileTool.readFile(templateFile, "UTF-8");

				// 替换title
				String resultHTML = templateHTML.replace("<title/>", "<title>"
						+ title + "</title>");

				// 替换keywords
				resultHTML = resultHTML.replace("<keywords/>",
						"<meta name=\"keywords\" content=\"" + key
								+ "\"></meta>");

				// 替换description
				resultHTML = resultHTML.replace("<description/>",
						"<meta name=\"description\" content=\"" + desc
								+ "\"></meta>");

				// 替换body
				resultHTML = resultHTML.replace("<body/>", "<body>"
						+ HTMLString + "</body>");

				// 静态页面根目录
				File htmlRoot = new File(realpath, FileTool.wash("temp-store."
						+ categoryId, "."));
				String thisDate = DateTrimmer.getYMD();
				File htmlFolder = new File(htmlRoot, thisDate);

				if (htmlFolder.exists() == false) {
					htmlFolder.mkdirs();
				}
				File htmlFile = new File(htmlFolder, infoid + ".html");
				FileTool.createNewFile(htmlFile, true);
				FileTool.makeFull(resultHTML, htmlFile, "UTF-8");

				String htmlFileUrl = "/temp-store/" + categoryId + "/"
						+ thisDate + "/" + infoid + ".html";
				// 暂存html url为后续操作使用
				cbh.getResource().put("htmlUrl", htmlFileUrl);
			} else {
				throw new MachiningException("template file(" + template
						+ ") is not exists.");
			}

		} else if (type == 1000 || type == 2000) {
			// 更新内容信息url字段,原数据处理过程已结束,原有connection已提交关闭
			BaseworkUtil util = new BaseworkUtil();
			SimpleBean4Table infoBean = new SimpleBean4TableImpl("APP_CMS_INFO");
			infoBean.getResource()
					.put("PK_ID", cbh.getResource().get("infoId"));
			infoBean.getResource().put("I_URL",
					cbh.getResource().get("htmlUrl"));

			Connection newConn = null;
			try {
				SystemDataSource ds = SystemDataSource.getInstance();
				newConn = ds.getConnection();
				util.manualUpdate1(infoBean, newConn);

				String uniqueid = StringTool.checkString(cbh.getResource().get(
						"INFOUNIQUEID"));
				if (!uniqueid.equals("")) {
					String sql = "UPDATE XSYSTEM_ANNEX SET ANNEX_OBJECT = ?, FK_ANNEX_ID = ? WHERE ANNEX_OBJECT = ? AND FK_ANNEX_ID = ?";
					new DataTrimmerI(newConn).execute(sql, "APP_CMS_INFO", cbh
							.getResource().get("infoId"), "INSERT_IMG",
							uniqueid);

					//清空附件临时主键
					ISystemContext.removeSessionObject(cbh.getRequest(),
							"INFOUNIQUEID");
				}

				SystemDataSource.commitConnection(newConn);
			} catch (Exception ex) {
				SystemDataSource.rollbackConnection(newConn);
				throw new MachiningException("update info html url error.", ex);
			} finally {
				SystemDataSource.closeConnection(newConn);
			}
		} else if (type == -3) {
			// 删除静态文件
			String id = (String) bean.getResource().get("PK_ID");

			this.deleteHTMLFile(id, conn);
		}
		return null;
	}

	private void deleteHTMLFile(String id, Connection conn) {
		// 删除静态文件
		BaseworkSelectUtil select = new BaseworkSelectUtil(conn);
		Map infoMap = select.selectSingleData("APP_CMS_INFO", id);

		String url = (String) infoMap.get("I_URL");

		File html = new File(realpath, FileTool.wash(url, "/"));

		html.delete();
	}
}
